﻿using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MvcPresenter.Models;

namespace MvcPresenter.Controllers
{
	[HandleError]
	public class HomeController : Controller
	{
		private static readonly Dictionary<string, string> ContentTypes = new Dictionary<string, string>
       	{
       		{".jpg", "image/jpeg"},
       		{".png", "image/png"},
       		{".gif", "image/gif"},
       		{".css", "text/css"},
       	};
		private IPresentationRepository _repository;

		protected override void Initialize(RequestContext requestContext)
		{
			base.Initialize(requestContext);

			// Serverプロパティなどの参照はInitialize以降じゃないと
            // できないので気をつけましょう
			_repository = new StoragePresentationRepository(Server.MapPath("~/App_Data"));
		}

		public ActionResult Index()
		{
			var list = _repository.List();
			return View(list);
		}

		[HttpPost]
		public ActionResult Index(Presentation presentaion)
		{
			if (ModelState.IsValid)
			{
				_repository.Create(presentaion);
				_repository.SubmitChanges();

				return RedirectToAction("Index");
			}

			return Index();
		}

		[HttpDelete]
		public ActionResult Delete(string id)
		{
			_repository.Delete(id);
			_repository.SubmitChanges();

			return RedirectToAction("Index");
		}

		public ActionResult Viewer(string id)
		{
			var presentation = _repository.GetByName(id);
			if (presentation == null)
				throw new HttpException(404, "File not found.");

			return View(presentation);
		}

		public ActionResult Resource(string path)
		{
			var filePath = Server.MapPath(string.Format("~/App_Data/{0}", path));
			if (!System.IO.File.Exists(filePath))
				throw new HttpException(404, "Resource not found.");

			var ext = Path.GetExtension(filePath);
			var contentType = ContentTypes.ContainsKey(ext)
			                     	? ContentTypes[ext]
			                     	: "application/octeat-stream";

			return File(filePath, contentType);
		}
	}
}